document.addEventListener("DOMContentLoaded", function () {
  const searchInput = document.getElementById("searchInput");
  const clearSearch = document.getElementById("clearSearch");
  const tabsList = document.getElementById("tabsList");
  const tabCount = document.getElementById("tabCount");

  let allTabs = [];

  // 加载所有标签页
  loadAllTabs();

  // 搜索功能
  searchInput.addEventListener("input", filterTabs);

  // 清空搜索
  clearSearch.addEventListener("click", () => {
    searchInput.value = "";
    filterTabs();
    searchInput.focus();
  });

  // 加载所有标签页
  function loadAllTabs() {
    chrome.tabs.query({}, (tabs) => {
      allTabs = tabs;
      renderTabs(tabs);
      tabCount.textContent = tabs.length;
    });
  }

  // 渲染标签页列表
  function renderTabs(tabs) {
    console.log(tabs);
    tabsList.innerHTML = "";

    if (tabs.length === 0) {
      tabsList.innerHTML = '<div class="no-tabs">没有找到匹配的标签页</div>';
      return;
    }

    tabs.forEach((tab) => {
      const tabItem = document.createElement("div");
      tabItem.className = "tab-item";

      // 创建 favicon 图片元素
      const favicon = document.createElement("img");
      favicon.className = "tab-favicon";
      favicon.src = tab.favIconUrl || "icons/icon48.png";
      favicon.addEventListener("error", () => {
        favicon.src = "icons/icon48.png";
      });

      // 创建标题和URL容器
      const textContainer = document.createElement("div");

      const title = document.createElement("div");
      title.className = "tab-title";
      title.textContent = tab.title;

      const url = document.createElement("div");
      url.className = "tab-url";
      url.textContent = tab.url;

      // 组装元素
      textContainer.appendChild(title);
      textContainer.appendChild(url);

      tabItem.appendChild(favicon);
      tabItem.appendChild(textContainer);

      // 添加点击事件
      tabItem.addEventListener("click", async () => {
        await chrome.windows.update(tab.windowId, { focused: true });
        chrome.tabs.update(tab.id, { active: true });
        window.close(); // 关闭弹出窗口
      });

      tabsList.appendChild(tabItem);
    });
  }

  // 过滤标签页
  function filterTabs() {
    const searchTerm = searchInput.value.toLowerCase();
    if (!searchTerm) {
      renderTabs(allTabs);
      return;
    }

    const filteredTabs = allTabs.filter((tab) => {
      return (
        tab.title.toLowerCase().includes(searchTerm) ||
        tab.url.toLowerCase().includes(searchTerm)
      );
    });

    renderTabs(filteredTabs);
  }
});
